package httpproxy.service;

import httpproxy.utils.RequestConverter;

import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

@Service
public class ProxyService {
	private static final String[] filterAddress = { "127.0.0.0", "127.0.0.1", "localhost" };

	public void proxyGetRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
		try {
			if (this.filterLocalRequest(servletRequest.getRequestURL().toString())) {
				return;
			}
			RequestConfig config = RequestConfig.custom().setCircularRedirectsAllowed(true).build();
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();
			HttpGet httpGet = RequestConverter.convertGetRequest(servletRequest);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			RequestConverter.convertResponse(response, servletResponse);
			httpclient.close(); 
			response.close();
		} catch (UnknownHostException e) {
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void proxyPostRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
		try {
			RequestConfig config = RequestConfig.custom().setCircularRedirectsAllowed(true).build();
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();
			HttpPost httpPost = RequestConverter.convertPostRequest(servletRequest);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			RequestConverter.convertResponse(response, servletResponse);
			httpclient.close(); 
			response.close();
		} catch (UnknownHostException e) {
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean filterLocalRequest(String address) {
		if (StringUtils.isEmpty(address)) {
			return true;
		}
		for (String one : filterAddress) {
			if (address.contains(one)) {
				return true;
			}
		}
		return false;
	}
}
